package com.example.springbatchsample.config;

import com.example.springbatchsample.database.Person;
import com.example.springbatchsample.etl.PersonItemProcessor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider;
import org.springframework.batch.item.database.JdbcBatchItemWriter;
import org.springframework.batch.item.database.builder.JdbcBatchItemWriterBuilder;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import javax.sql.DataSource;

// tag::setup[]
@Configuration
//启动批处理
@EnableBatchProcessing
@Slf4j
public class BatchConfiguration {

    /**
     * 创建任务对象的对象
     */
    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    /**
     * 任务的执行由Step决定,
     * 这个用来创建Step
     */
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    // end::setup[]

    // tag::readerwriterprocessor[]
    @Bean
    public FlatFileItemReader<Person> csvReader() {
        //从csv文件读取两列信息作为名字
        return new FlatFileItemReaderBuilder<Person>()
                .name("personItemReader")
                .resource(new ClassPathResource("sample-data.csv"))
                .delimited()
                .names("firstName", "lastName")
                .fieldSetMapper(new BeanWrapperFieldSetMapper<Person>() {{
                    setTargetType(Person.class);
                }})
                .build();
    }

    @Bean
    public PersonItemProcessor processor() {
        return new PersonItemProcessor();
    }

    @Bean
    public JdbcBatchItemWriter<Person> writer(DataSource dataSource) {
        return new JdbcBatchItemWriterBuilder<Person>()
                .itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>())
                .sql("INSERT INTO people (first_name, last_name) VALUES (:firstName, :lastName)")
                .dataSource(dataSource)
                .build();
    }
    // end::readerwriterprocessor[]

    // tag::jobstep[]

    /**
     * 这是一个任务
     *
     * @param listener 监听器
     * @param step1    步骤，来自 {@link #step1(org.springframework.batch.item.database.JdbcBatchItemWriter)}
     * @return
     */
    // @Bean
    public Job importUserJob(JobCompletionNotificationListener listener, Step step1,
            Step stepxx) {
        return jobBuilderFactory
                //起名
                .get("importUserJob")
                .incrementer(new RunIdIncrementer())
                .listener(listener)
                .flow(step1)
                .next(stepxx)
                .end()
                .build();
    }
    @Bean
    public MyItemWriter<String> myItemWriter(){
        return new MyItemWriter<>();
    }
    @Bean
    public Job chunkJob(JobCompletionNotificationListener listener,
            Step stepReader) {
        return jobBuilderFactory
                //起名
                .get("chunkJob")
                .flow(stepReader)
                .end()
                .build();
    }

    @Bean
    public Step stepReader(MyItemReader myItemReader, MyItemWriter<String> myItemWriter) {
        return stepBuilderFactory.get("stepReader")
                .<String, String>chunk(2)
                .reader(myItemReader)
                .writer(myItemWriter)
                .build();
    }

    @Bean
    public Step stepxx() {
        return stepBuilderFactory.get("stepxx")
                .tasklet((stepContribution, chunkContext) -> {
                    System.out.println("hello world");
                    return RepeatStatus.FINISHED;
                }).build();
    }

    @Bean
    public Step step1(JdbcBatchItemWriter<Person> writer) {
        return stepBuilderFactory
                //起名
                .get("step1")
                .<Person, Person>chunk(10)
                .reader(csvReader())
                .processor(processor())
                .writer(writer)
                .build();
    }
    // end::jobstep[]
}